import React, { useEffect, useState } from 'react'
import { Button, Form, Select, Row, Col, Input, Card, Table, message, } from 'antd';
import { SearchOutlined } from "@ant-design/icons"
import { useNavigate } from 'react-router-dom';

import {
  hospitalListGetDataRequest,
  getProvinceRequest,
  getCityOrDistrictCodeRequest,
  getHosListTypeRequest,
  changeHosListStatusRequest
} from "@api/hospital/hospitalList"

import type {
  hospitalListParamType,
  hospitalContetType,
  hospitalItemType,
  provinceType,
} from "@api/hospital/model/hospitalListType"

export default function HospitalList() {
  //定义编程式路由跳转
  const navigator = useNavigate()
  //创建表单实例
  const [form] = Form.useForm()
  //定义加载状态
  const [isloading, setIsloading] = useState(false)
  //定义重新加载页码状态
  const [reload, setReload] = useState(true)
  //定义初始页码
  const [page, setPage] = useState(1)
  //定义每页数据条数
  const [limit, setLimit] = useState(3)
  //定义数据总条数
  const [total, setTotal] = useState(0)
  //定义获取列表的params参数
  const [search, setSearch] = useState<hospitalListParamType>({})
  //定义医院列表数据内容
  const [content, Setcontent] = useState<hospitalContetType>([])
  //定义医院的类型
  const [type, setType] = useState<provinceType>([])
  //定义三级联动之省的数据列表
  const [province, setProvince] = useState<provinceType>([])
  //定义三级联动之市的数据列表
  const [city, setCity] = useState<provinceType>([])
  //定义三级联动之县的数据列表
  const [district, setDistrict] = useState<provinceType>([])

  //初始获取列表数据
  useEffect(() => {
    const initGethosList = async () => {
      setIsloading(true)
      const hosList = await hospitalListGetDataRequest({ page, limit }, search)
      //设置医院列表数据状态
      Setcontent(hosList.content)
      //设置数据总数状态
      setTotal(hosList.totalElements)
      //结束加载状态
      setIsloading(false)
    }
    initGethosList()
  }, [page, limit, search, reload])
  //初始获取医院类型的信息
  useEffect(() => {
    const initGetHosType = async () => {
      const type = await getHosListTypeRequest()
      setType(type)
    }
    initGetHosType()
  }, [])

  //初始获取省份信息
  useEffect(() => {
    const getProvince = async () => {
      const result = await getProvinceRequest()
      setProvince(result)
    }
    getProvince()
  }, [])


  //三级联动之获取市的回调
  const getCityCodeHandle = (id: string) => {
    const getCity = async () => {
      const city = await getCityOrDistrictCodeRequest(id)
      setCity(city)
      //选择后表单原先内容清空
      form.setFieldsValue({ cityCode: '', districtCode: '' })
      //二次选择省会后 将县的数据清空 否则数据残留
      setDistrict([])
    }
    getCity()
  }
  //三级联动之获取县的回调
  const getDistrictCodeHandle = (id: string) => {
    const getDistrictCode = async () => {
      const district = await getCityOrDistrictCodeRequest(id)
      setDistrict(district)
      // 选择后表单原先内容清空
      form.setFieldsValue({ districtCode: '' })
    }
    getDistrictCode()
  }

  //查询医院列表的回调
  const searchHandle = (search: hospitalListParamType) => {
    setSearch(search)
  }

  //改变上下线状态的回调
  const changeStatusHandle = (id: string, status: number) => {
    return async () => {
      await changeHosListStatusRequest(id, status)
      
      //改变状态后刷新页面
      setReload(!reload)
      message.success(status?'上线成功':'下线成功')
    }
  }


  const columns = [
    {
      title: '序号',
      dataIndex: 'name',
      width: 30,
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院logo',
      width: 120,
      render(_: any, data: hospitalItemType) {
        return <img width={100} src={`data:image/jpeg;base64,${data.logoData}`} alt="" />
      }
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
      width: 220
    },
    {
      title: '医院等级',
      width: 120,
      render(_: any, data: hospitalItemType) {
        return data.param.hostypeString
      }

    },
    {
      title: '详细地址',
      width: 220,
      render(_: any, data: hospitalItemType) {
        return data.param.fullAddress
      }
    },
    {
      title: '状态',
      width: 30,
      render(_: any, data: hospitalItemType) {
        return data.status === 0 ? '已下线' : '已上线'
      }

    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 220,
    },
    {
      title: '操作',
      render(_: any, data: hospitalItemType) {
        return <div>
          <Button htmlType="button" type="primary" style={{ marginRight: 20 }} onClick={()=>{navigator(`/syt/hospital/hospitalShow/${data.id}`)}}>
            详情
          </Button>
          <Button htmlType="button" type="primary" style={{ marginRight: 20 }}>
            排班
          </Button>
          <Button htmlType="button" type="primary" onClick={changeStatusHandle(data.id, (data.status) ? 0 : 1)}>
            {
              data.status === 0 ? '上线' : '下线'
            }
          </Button>
        </div>
      }

    },
  ];

  return (
    <Card>
      <Form
        onFinish={searchHandle}
        form={form}
        name="control-hooks"
      >
        <Row gutter={10}>
          <Col span={4} >
            <Form.Item name="province" >
              <Select
                placeholder="请选择省"
                onChange={getCityCodeHandle}
              >
                {province.map(item => {
                  return <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>
                })}
              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="cityCode">
              <Select placeholder="请选择市" onChange={getDistrictCodeHandle}>

                {city.map(item => {
                  return <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>
                })}

              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="districtCode">
              <Select placeholder="请选择县/区">

                {district.map(item => {
                  return <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>
                })}

              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="hosname">
              <Input placeholder='医院名称' />
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="hoscode">
              <Input placeholder='医院编号' />
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="hostype">
              <Select placeholder="医院类型">
                {
                  type.map(item => {
                    return <Select.Option key={item.id} value={item.value}>{item.name}</Select.Option>
                  })
                }
              </Select>
            </Form.Item>
          </Col>

          <Col span={4}>
            <Form.Item name="status">
              <Select placeholder="医院状态">
                <Select.Option value={1}>上线</Select.Option>
                <Select.Option value={0}>下线</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ marginRight: 20 }} icon={<SearchOutlined />}>
              查询
            </Button>
            <Button htmlType="reset" onClick={() => { setReload(!reload) }}>
              清空
            </Button>
          </Form.Item>
        </Row>
      </Form>
      <Table
        loading={isloading}
        columns={columns}
        dataSource={content}
        bordered
        rowKey="id"
        scroll={{ x: 1300 }}
        pagination={{
          current: page,
          pageSize: limit,
          pageSizeOptions: [3, 5, 8, 10],
          showSizeChanger: true,
          total,
          showTotal: (total) => `共${total}条数据`,
          onChange(page, pageSize) {
            setPage(page)
            setLimit(pageSize)
          }
        }}
      />;
    </Card>
  )
}
